package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysParamSearchOutputDto;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.LabFeeItem;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabReqMain;
import com.ysd.lis.entity.lab.LabReqdetail;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysOrgDepartmentMapper;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.bac.BacTestCultureMediumService;
import com.ysd.lis.service.bac.BacTestResultService;
import com.ysd.lis.service.bac.BacTestWorkFlowNodeService;
import com.ysd.lis.service.bac.BacTestWorkFlowService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.*;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LabReqMainBacServiceImpl extends ServiceImpl<LabReqMainMapper, LabReqMain> {
    private static final Logger logger = LoggerFactory.getLogger(LabReqMainBacServiceImpl.class);
    @Autowired
    BacReqPurposeMapper bacReqPurposeMapper;
    @Autowired
    BacReqPurposeDetailMapper bacReqPurposeDetailMapper;//微生物检验目的首选备选方案
    @Autowired
    BacWorkFlowMapper bacWorkFlowMapper;//方案流程
    @Autowired
    BacWorkFlowNodeMapper bacWorkFlowNodeMapper;//方案流程节点
    @Autowired
    BacCultureCombinationMapper bacCultureCombinationMapper;//培养基组合
    @Autowired
    BacCultureCombinaRelMapper bacCultureCombinaRelMapper;//培养基组合明细
    @Autowired
    BacCultureMediumMapper bacCultureMediumMapper;//培养基
    @Autowired
    BacTestWorkFlowMapper bacTestWorkFlowMapper;//检验选用方案
    @Autowired
    BacTestWorkFlowService bacTestWorkFlowService;//检验选用方案
    @Autowired
    BacTestWorkFlowNodeMapper bacTestWorkFlowNodeMapper;//检验选用方案对用节点
    @Autowired
    BacTestWorkFlowNodeService bacTestWorkFlowNodeService;//检验选用方案对用节点
    @Autowired
    BacTestCultureMediumMapper bacTestCultureMediumMapper;//检验选用培养基
    @Autowired
    BacTestCultureMediumService bacTestCultureMediumService;//检验选用培养基
    @Autowired
    SysRuleSetService sysRuleSetService;//编码规则服务
    @Autowired
    BacReqPurposeFeeItemMapper bacReqPurposeFeeItemMapper;
    @Autowired
    private LabFeeItemMapper labFeeItemMapper;//申请项目
    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    LabReqStateService labReqStateService;
    @Autowired
    LabProcessSetService labProcessSetService;
    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    LabProcessSetMapper labProcessSetMapper;
    @Autowired
    LabTatGroupruleService labTatGroupruleService;
    @Autowired
    LabFinanceSalesFeeitemService labFinanceSalesFeeitemService;
    @Autowired
    LabTatNodeService labTatNodeService;
    @Autowired
    LabTatNodeMapper labTatNodeMapper;
    @Autowired
    LabHisReqMapper labHisReqMapper;

    @Autowired
    LabReqMainService labReqMainService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    LabMainStateService labMainStateService;

    @Autowired
    LabReqdetailMapper labReqdetailMapper;

    @Autowired
    RedisSysParamHelper redisSysParamHelper;
    @Autowired
    BacFlowDefResultMapper bacFlowDefResultMapper;

    @Autowired
    BacBloodCultrueMapper bacBloodCultrueMapper;
    @Autowired
    BacTestResultService bacTestResultService;

    @Autowired
    BacStainingResultMapper bacStainingResultMapper;


    /*微生物:计算应用方案、培养基等*/
    public Boolean CalcWkflwCultures(LabReqMain entry, LabMaininfo labMaininfo) {
        List<BacTestWorkFlow> BacTestWorkFlowList = new ArrayList<>();
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = new ArrayList<>();
        List<BacTestCultureMedium> BacTestCultureMediumList = new ArrayList<>();
        logger.info("微生物签收:开始 ");
        /*第一步：查询检验目的对照的方案步骤培养基组合插入到方案 步骤表 所用培养基*/
        if (ToolsUtils.isNotEmpty(entry.getPurposeNo())) {
            logger.info("微生物签收:11111111111");
            /*1、查询出检验目的*/
            MPJLambdaWrapper<BacReqPurpose> bacReqPurposeWrapper = new MPJLambdaWrapper<>();
            bacReqPurposeWrapper.eq(BacReqPurpose::getDelFlag, 0);
            bacReqPurposeWrapper.eq(BacReqPurpose::getPurposeNo, entry.getPurposeNo());
            List<BacReqPurpose> reqPurposeEntries = bacReqPurposeMapper.selectList(bacReqPurposeWrapper);
            BacReqPurpose reqPurposeEntry = reqPurposeEntries.isEmpty() ? null : reqPurposeEntries.get(0);

            /*2、获取检验目的默认的方案、培养基组合 及流程节点、培养基*/
            BacWorkFlow reqWorkFlowEntry = null;
            List<BacWorkFlowNode> reqWorkFlowNodeList = null;
            if (!BeanUtil.isEmpty(reqPurposeEntry) && StringUtils.isNotEmpty(reqPurposeEntry.getFlowNo())) {
                MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
                bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
                bacWorkFlowWrapper.and(p -> p.eq(BacWorkFlow::getWorkFlowCode, reqPurposeEntry.getFlowNo()).eq(BacWorkFlow::getDelFlag, 0));
                reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);

                /*获取流程方案节点*/
                MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
                bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
                bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
                bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
                reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
            }

            /*3、获取培养基、培养基组合*/
            BacCultureCombination reqCultureCombinationEntry = null;
            List<BacCultureCombinaRel> bacCultureCombinaRelList = null;
            if (!BeanUtil.isEmpty(reqPurposeEntry) && StringUtils.isNotEmpty(reqPurposeEntry.getCulComninaNo())) {
                MPJLambdaWrapper<BacCultureCombination> bacCultureCombinationWrapper = new MPJLambdaWrapper<>();
                bacCultureCombinationWrapper.eq(BacCultureCombination::getDelFlag, 0);
                bacCultureCombinationWrapper.eq(BacCultureCombination::getCode, reqPurposeEntry.getCulComninaNo());
                List<BacCultureCombination> reqCultureCombinationEntries = bacCultureCombinationMapper.selectList(bacCultureCombinationWrapper);
                reqCultureCombinationEntry = reqCultureCombinationEntries.isEmpty() ? null : reqCultureCombinationEntries.get(0);

                //bacCultureCombinaRelMapper
                MPJLambdaWrapper<BacCultureCombinaRel> BacCultureCombinaRelWrapper = new MPJLambdaWrapper<>();
                BacCultureCombinaRelWrapper.eq(BacCultureCombinaRel::getDelFlag, 0);
                BacCultureCombinaRelWrapper.and(p -> p.eq(BacCultureCombinaRel::getCulCombinaNo, reqPurposeEntry.getCulComninaNo()).eq(BacCultureCombinaRel::getDelFlag, 0));
                BacCultureCombinaRelWrapper.selectAll(BacCultureCombinaRel.class);
                BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
                BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
                BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getType, BacCultureCombinaRel::getKind);
                BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getCode, BacCultureCombinaRel::getCombinationNo);
                BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getName, BacCultureCombinaRel::getCombinationNa);
                BacCultureCombinaRelWrapper.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getCode, BacCultureCombinaRel::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
                BacCultureCombinaRelWrapper.leftJoin(BacCultureCombination.class, "tab2", p -> p.eq(BacCultureCombination::getCode, BacCultureCombinaRel::getCulCombinaNo).eq(BacCultureCombination::getDelFlag, 0));

                bacCultureCombinaRelList = bacCultureCombinaRelMapper.selectList(BacCultureCombinaRelWrapper);
            }

            /*4、插入检验 选用方案  节点  培养基信息*/


            String bacTestWkflwId = IdUtil.getSnowflake().nextId() + "";

            //流程方案
            if (reqWorkFlowEntry != null && BeanUtil.isNotEmpty(reqWorkFlowEntry)) {
                BacTestWorkFlow m = new BacTestWorkFlow();
                m.setId(bacTestWkflwId);
                //m.setReqMainId(entry.getId());
                //m.setRptGroup();
                m.setReqNo(entry.getReqNo());
                m.setWorkFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                m.setWorkFlowNa(reqWorkFlowEntry.getWorkFlowName());
                m.setSeq(1);
                m.setCulCombinaNos(reqCultureCombinationEntry.getCode());
                if (BeanUtil.isNotEmpty(labMaininfo)) {
                    m.setRptGroup(labMaininfo.getRptGroup());
                    m.setSampleda(labMaininfo.getSampleda());
                    m.setSampleNo(labMaininfo.getSampleNo());
                }
                BacTestWorkFlowList.add(m);
            }

            //流程方案节点
            if (!BeanUtil.isEmpty(reqWorkFlowNodeList) && !reqWorkFlowNodeList.isEmpty()) {
                for (BacWorkFlowNode m : reqWorkFlowNodeList) {
                    BacTestWorkFlowNode op = new BacTestWorkFlowNode();
                    op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                    op.setNodeNo(m.getNodeCode());
                    op.setReqNo(entry.getReqNo());
                    op.setSeq(m.getSeq());
                    if (ToolsUtils.isNotEmpty(labMaininfo)) {
                        op.setRptGroup(labMaininfo.getRptGroup());
                        op.setSampleda(labMaininfo.getSampleda());
                        op.setSampleNo(labMaininfo.getSampleNo());
                    }
                    BacTestWorkFlowNodeList.add(op);
                }
            }

            //选用的培养基
            if (!BeanUtil.isEmpty(bacCultureCombinaRelList) && !bacCultureCombinaRelList.isEmpty()) {
                for (BacCultureCombinaRel m : bacCultureCombinaRelList) {
                    BacTestCultureMedium op = new BacTestCultureMedium();
//                    op.setReqMainId(entry.getId());
                    op.setReqNo(entry.getReqNo());
                    op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                    //op.setWorkFlowNodeId(m.getId());
                    String a = sysRuleSetService.createRuleCodeList("CultuBarCode", 1).get(0);
                    op.setAutoNo(a);
                    op.setCultureNo(m.getCultrueNo());
                    op.setCultureNa(m.getCultrueName());
                    op.setCultureCombinNo(m.getCombinationNo());
                    op.setCultureCombinNa(m.getCombinationNa());
                    op.setIsPrintLabel(0);
                    op.setPrintLabelCount(0);
                    //op.setWorkFlowNodeId(m.get);
                    try {
                        op.setSeq(Integer.parseInt(m.getOrderNum()));
                    } catch (Exception e) {
                        //TODO
                    }
                    if (ToolsUtils.isNotEmpty(labMaininfo)) {
                        op.setRptGroup(labMaininfo.getRptGroup());
                        op.setSampleda(labMaininfo.getSampleda());
                        op.setSampleNo(labMaininfo.getSampleNo());
                    }
                    BacTestCultureMediumList.add(op);
                }
            }

            saveWkflwNodesCultuMediums(BacTestWorkFlowList, BacTestWorkFlowNodeList, BacTestCultureMediumList);
        } else {
            if (ToolsUtils.isEmpty(entry.getPurposeNo())) {
                /*查询出申请项目对照的检验目的*/
                logger.info("微生物签收:22222222222222 ");
                if (ToolsUtils.isEmpty(entry.getSampleType()) || ToolsUtils.isEmpty(entry.getReqNo())) {
                    logger.info("微生物签收:333333333333333 ");
                    bacTestUseDefaultWorkFlowWithPurpose(entry, labMaininfo);
                } else {
                    logger.info("微生物签收:44444444444444 ");
                    MPJLambdaWrapper<LabReqdetail> reqDetailWrapper = new MPJLambdaWrapper<>();
                    reqDetailWrapper.eq(LabReqdetail::getDelFlag, 0);
                    reqDetailWrapper.eq(LabReqdetail::getReqNo, entry.getReqNo());
                    List<LabReqdetail> reqDetails = labReqdetailMapper.selectList(reqDetailWrapper);
                    List<String> feeCodes = reqDetails.stream().map(LabReqdetail::getFeeCode).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(feeCodes)) {
                        logger.info("微生物签收:5555555555555555555 ");
                        bacTestUseDefaultWorkFlowWithPurpose(entry, labMaininfo);
                    } else {
                        logger.info("微生物签收:66666666666666 ");
                        MPJLambdaWrapper<BacReqPurposeFeeItem> pvsfWrapper = new MPJLambdaWrapper<>();
                        pvsfWrapper.selectAll(BacReqPurposeFeeItem.class)
                                        .selectAs(BacReqPurpose::getSeq, BacReqPurposeFeeItem::getPurposeSeq);
                        pvsfWrapper.leftJoin(BacReqPurpose.class, "tab1", p -> p.eq(BacReqPurpose::getPurposeNo, BacReqPurposeFeeItem::getPurposeNo).eq(BacReqPurpose::getDelFlag, 0));

                        pvsfWrapper.eq(BacReqPurposeFeeItem::getDelFlag, 0);
                        pvsfWrapper.eq(BacReqPurposeFeeItem::getSampleTypeCode, entry.getSampleType());
                        pvsfWrapper.in(BacReqPurposeFeeItem::getFeeCode, feeCodes);
                        List<BacReqPurposeFeeItem> pvsfList = bacReqPurposeFeeItemMapper.selectList(pvsfWrapper);

                        if (CollectionUtils.isEmpty(pvsfList)) {
                            logger.info("微生物签收:77777777777777777 ");
                            bacTestUseDefaultWorkFlowWithPurpose(entry, labMaininfo);
                        } else {
                            logger.info("微生物签收:88888888888888888888 ");
                            String purposeNo = "";
                            //查看pvsfList中有几条purposeNo
                            Set<String> purposeNoSet = pvsfList.stream().map(BacReqPurposeFeeItem::getPurposeNo).collect(Collectors.toSet());
                            //如果有一条则取出purposeNoSet的值
                            if (purposeNoSet.size() == 1) {
                                purposeNo = purposeNoSet.iterator().next();
                            }else {
                                //purposeNo分组 查看分组后的条数，取条数最多的purposeNo
                                Map<String, List<BacReqPurposeFeeItem>> pvsfMap = pvsfList.stream().collect(Collectors.groupingBy(BacReqPurposeFeeItem::getPurposeNo));
                                //获取pvsfMap中list集合中条数最多的,如果条数一样多则取PurposeSeq最大的key
                                Optional<String> result = pvsfMap.entrySet().stream()
                                        .max(Comparator
                                                .comparingInt((Map.Entry<String, List<BacReqPurposeFeeItem>> e) -> e.getValue().size())
                                                .thenComparingInt((Map.Entry<String, List<BacReqPurposeFeeItem>> e) -> e.getValue().get(0).getPurposeSeq())
                                        )
                                        .map(Map.Entry::getKey);

                                purposeNo = result.orElse(null); // 若 Map 为空则返回 null

                            }
                            bacCalcPurposeByScanReqNo1(entry, labMaininfo, purposeNo);
                        }
                    }
                }

            } else {
                logger.info("微生物签收:999999999999999999999 ");
                bacTestUseDefaultWorkFlowWithPurpose(entry, labMaininfo);
            }
        }

        return true;
    }

    public Boolean bacCalcPurposeByScanReqNo1(LabReqMain entry, LabMaininfo labMaininfo, String purposeNo) {
        List<BacTestWorkFlow> BacTestWorkFlowList = new ArrayList<>();
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = new ArrayList<>();
        List<BacTestCultureMedium> BacTestCultureMediumList = new ArrayList<>();

        /*1、查询出检验目的*/
        MPJLambdaWrapper<BacReqPurpose> bacReqPurposeWrapper = new MPJLambdaWrapper<>();
        bacReqPurposeWrapper.eq(BacReqPurpose::getDelFlag, 0);
        bacReqPurposeWrapper.eq(BacReqPurpose::getPurposeNo, purposeNo);
        List<BacReqPurpose> reqPurposeEntries = bacReqPurposeMapper.selectList(bacReqPurposeWrapper);
        BacReqPurpose reqPurposeEntry = reqPurposeEntries.isEmpty() ? null : reqPurposeEntries.get(0);

        /*2、获取检验目的默认的方案、培养基组合 及流程节点、培养基*/
        BacWorkFlow reqWorkFlowEntry = null;
        List<BacWorkFlowNode> reqWorkFlowNodeList = null;
        if (!BeanUtil.isEmpty(reqPurposeEntry) && StringUtils.isNotEmpty(reqPurposeEntry.getFlowNo())) {
            MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
            bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
            bacWorkFlowWrapper.and(p -> p.eq(BacWorkFlow::getWorkFlowCode, reqPurposeEntry.getFlowNo()).eq(BacWorkFlow::getDelFlag, 0));
            reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);

            /*获取流程方案节点*/
            MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
            bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
            bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
            bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
            reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
        }

        /*3、获取培养基、培养基组合*/
        BacCultureCombination reqCultureCombinationEntry = null;
        List<BacCultureCombinaRel> bacCultureCombinaRelList = null;
        if (!BeanUtil.isEmpty(reqPurposeEntry) && StringUtils.isNotEmpty(reqPurposeEntry.getCulComninaNo())) {
            MPJLambdaWrapper<BacCultureCombination> bacCultureCombinationWrapper = new MPJLambdaWrapper<>();
            bacCultureCombinationWrapper.eq(BacCultureCombination::getDelFlag, 0);
            bacCultureCombinationWrapper.eq(BacCultureCombination::getCode, reqPurposeEntry.getCulComninaNo());
            List<BacCultureCombination> reqCultureCombinationEntries = bacCultureCombinationMapper.selectList(bacCultureCombinationWrapper);
            reqCultureCombinationEntry = reqCultureCombinationEntries.isEmpty() ? null : reqCultureCombinationEntries.get(0);

            //bacCultureCombinaRelMapper
            MPJLambdaWrapper<BacCultureCombinaRel> BacCultureCombinaRelWrapper = new MPJLambdaWrapper<>();
            BacCultureCombinaRelWrapper.eq(BacCultureCombinaRel::getDelFlag, 0);
            BacCultureCombinaRelWrapper.and(p -> p.eq(BacCultureCombinaRel::getCulCombinaNo, reqPurposeEntry.getCulComninaNo()).eq(BacCultureCombinaRel::getDelFlag, 0));
            BacCultureCombinaRelWrapper.selectAll(BacCultureCombinaRel.class);
            BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
            BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getType, BacCultureCombinaRel::getKind);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getCode, BacCultureCombinaRel::getCombinationNo);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getName, BacCultureCombinaRel::getCombinationNa);
            BacCultureCombinaRelWrapper.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getCode, BacCultureCombinaRel::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
            BacCultureCombinaRelWrapper.leftJoin(BacCultureCombination.class, "tab2", p -> p.eq(BacCultureCombination::getCode, BacCultureCombinaRel::getCulCombinaNo).eq(BacCultureCombination::getDelFlag, 0));

            bacCultureCombinaRelList = bacCultureCombinaRelMapper.selectList(BacCultureCombinaRelWrapper);
        }

        /*4、插入检验 选用方案  节点  培养基信息*/


        String bacTestWkflwId = IdUtil.getSnowflake().nextId() + "";

        //流程方案
        if (reqWorkFlowEntry != null && BeanUtil.isNotEmpty(reqWorkFlowEntry)) {
            BacTestWorkFlow m = new BacTestWorkFlow();
            m.setId(bacTestWkflwId);
            //m.setReqMainId(entry.getId());
            //m.setRptGroup();
            m.setReqNo(entry.getReqNo());
            m.setWorkFlowNo(reqWorkFlowEntry.getWorkFlowCode());
            m.setWorkFlowNa(reqWorkFlowEntry.getWorkFlowName());
            m.setSeq(1);
            m.setCulCombinaNos(reqCultureCombinationEntry.getCode());
            if (BeanUtil.isNotEmpty(labMaininfo)) {
                m.setRptGroup(labMaininfo.getRptGroup());
                m.setSampleda(labMaininfo.getSampleda());
                m.setSampleNo(labMaininfo.getSampleNo());
            }
            BacTestWorkFlowList.add(m);
        }

        //流程方案节点
        if (!BeanUtil.isEmpty(reqWorkFlowNodeList) && !reqWorkFlowNodeList.isEmpty()) {
            for (BacWorkFlowNode m : reqWorkFlowNodeList) {
                BacTestWorkFlowNode op = new BacTestWorkFlowNode();
                op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                op.setNodeNo(m.getNodeCode());
                op.setReqNo(entry.getReqNo());
                op.setSeq(m.getSeq());
                if (ToolsUtils.isNotEmpty(labMaininfo)) {
                    op.setRptGroup(labMaininfo.getRptGroup());
                    op.setSampleda(labMaininfo.getSampleda());
                    op.setSampleNo(labMaininfo.getSampleNo());
                }
                BacTestWorkFlowNodeList.add(op);
            }
        }

        //选用的培养基
        if (!BeanUtil.isEmpty(bacCultureCombinaRelList) && !bacCultureCombinaRelList.isEmpty()) {
            for (BacCultureCombinaRel m : bacCultureCombinaRelList) {
                BacTestCultureMedium op = new BacTestCultureMedium();
//                    op.setReqMainId(entry.getId());
                op.setReqNo(entry.getReqNo());
                op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                //op.setWorkFlowNodeId(m.getId());
                String a = sysRuleSetService.createRuleCodeList("CultuBarCode", 1).get(0);
                op.setAutoNo(a);
                op.setCultureNo(m.getCultrueNo());
                op.setCultureNa(m.getCultrueName());
                op.setCultureCombinNo(m.getCombinationNo());
                op.setCultureCombinNa(m.getCombinationNa());
                op.setIsPrintLabel(0);
                op.setPrintLabelCount(0);
                //op.setWorkFlowNodeId(m.get);
                try {
                    op.setSeq(Integer.parseInt(m.getOrderNum()));
                } catch (Exception e) {
                    //TODO
                }
                if (ToolsUtils.isNotEmpty(labMaininfo)) {
                    op.setRptGroup(labMaininfo.getRptGroup());
                    op.setSampleda(labMaininfo.getSampleda());
                    op.setSampleNo(labMaininfo.getSampleNo());
                }
                BacTestCultureMediumList.add(op);
            }
        }

        saveWkflwNodesCultuMediums(BacTestWorkFlowList, BacTestWorkFlowNodeList, BacTestCultureMediumList);

        if (BeanUtil.isNotEmpty(entry)) {
            entry.setPurposeNo(purposeNo);
            entry.setIsSign(new BigDecimal(1));
            SysUser sysUser = RedisUserManager.getUser();
            entry.setSignerDoctor(sysUser.getUsername());
            entry.setSignerDoctor(sysUser.getRealname());
            this.saveOrUpdate(entry);
            if (ToolsUtils.isNotEmpty(entry.getIsManual()) && entry.getIsManual().intValue() != 1) {
                try {
                    LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SysInterface::getDelFlag, 0);
                    wrapper.eq(SysInterface::getIsEnable, 1);
                    wrapper.eq(SysInterface::getOrgId, entry.getOrgId());
                    List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                    List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                    //标本签收
                    if (CollectionUtils.isNotEmpty(collect)) {
                        for (String webUrl : collect) {
                            //调用修改状态接口
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("status", "0304");
                            updateMap.put("reqNo", entry.getReqNo());
                            updateMap.put("patType", entry.getPatType());
                            updateMap.put("username", sysUser.getUsername());
                            updateMap.put("realname", sysUser.getRealname());
                            updateMap.put("orgId", sysUser.getOrgId());
                            updateMap.put("chargeType", "1");
                            //标本签收
                            String hl7Url = webUrl + "/public/sampleReceive";
                            HttpUtil.createPost(hl7Url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

                            String updateUrl = webUrl + "/public/updateReportStatus";
                            HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            //调用执行医嘱确费接口
                            if ("3".equals(entry.getPatType())) {
                                String yzqfUrl = webUrl + "/yzqf";
                                HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }
        return true;
    }

    /*微生物:保存流程方案、流程方案节点、培养基*/
    public boolean saveWkflwNodesCultuMediums(List<BacTestWorkFlow> BacTestWorkFlowList, List<BacTestWorkFlowNode> BacTestWorkFlowNodeList, List<BacTestCultureMedium> BacTestCultureMediumList) {
        for (BacTestWorkFlow m : BacTestWorkFlowList) {
            LambdaQueryWrapper<BacTestWorkFlow> workFlowWrapper = new LambdaQueryWrapper<>();
            workFlowWrapper.eq(BacTestWorkFlow::getReqNo, m.getReqNo());
            workFlowWrapper.eq(StringUtils.isNotBlank(m.getSampleNo()),BacTestWorkFlow::getSampleNo, m.getSampleNo());
            workFlowWrapper.eq(StringUtils.isNotBlank(m.getRptGroup()),BacTestWorkFlow::getRptGroup, m.getRptGroup());
            workFlowWrapper.eq(Objects.nonNull(m.getSampleda()),BacTestWorkFlow::getSampleda, m.getSampleda());
            workFlowWrapper.eq(BacTestWorkFlow::getWorkFlowNo, m.getWorkFlowNo());
            workFlowWrapper.eq(BacTestWorkFlow::getDelFlag, 0);
            bacTestWorkFlowService.saveOrUpdate(m,workFlowWrapper);
        }

        for (BacTestWorkFlowNode m : BacTestWorkFlowNodeList) {
            LambdaQueryWrapper<BacTestWorkFlowNode> workFlowWrapper = new LambdaQueryWrapper<>();
            workFlowWrapper.eq(BacTestWorkFlowNode::getReqNo, m.getReqNo());
            workFlowWrapper.eq(StringUtils.isNotBlank(m.getSampleNo()),BacTestWorkFlowNode::getSampleNo, m.getSampleNo());
            workFlowWrapper.eq(StringUtils.isNotBlank(m.getRptGroup()),BacTestWorkFlowNode::getRptGroup, m.getRptGroup());
            workFlowWrapper.eq(Objects.nonNull(m.getSampleda()),BacTestWorkFlowNode::getSampleda, m.getSampleda());
            workFlowWrapper.eq(BacTestWorkFlowNode::getTestFlowNo, m.getTestFlowNo());
            workFlowWrapper.eq(BacTestWorkFlowNode::getNodeNo, m.getNodeNo());
            workFlowWrapper.eq(BacTestWorkFlowNode::getDelFlag, 0);
            bacTestWorkFlowNodeService.saveOrUpdate(m, workFlowWrapper);
        }

        for (BacTestCultureMedium m : BacTestCultureMediumList) {
            LambdaQueryWrapper<BacTestCultureMedium> workFlowWrapper = new LambdaQueryWrapper<>();
            workFlowWrapper.eq(BacTestCultureMedium::getReqNo, m.getReqNo());
            workFlowWrapper.eq(StringUtils.isNotBlank(m.getSampleNo()),BacTestCultureMedium::getSampleNo, m.getSampleNo());
            workFlowWrapper.eq(StringUtils.isNotBlank(m.getRptGroup()),BacTestCultureMedium::getRptGroup, m.getRptGroup());
            workFlowWrapper.eq(Objects.nonNull(m.getSampleda()),BacTestCultureMedium::getSampleda, m.getSampleda());
            workFlowWrapper.eq(BacTestCultureMedium::getTestFlowNo, m.getTestFlowNo());
            workFlowWrapper.eq(BacTestCultureMedium::getCultureNo, m.getCultureNo());
            workFlowWrapper.eq(BacTestCultureMedium::getDelFlag, 0);
            bacTestCultureMediumService.saveOrUpdate(m, workFlowWrapper);
        }

        return true;
    }


    /*微生物检验采用默认方案-默认检验目的*/
    public Boolean bacTestUseDefaultWorkFlowWithPurpose(LabReqMain reqMain, LabMaininfo labMaininfo) {
        List<BacTestWorkFlow> BacTestWorkFlowList = new ArrayList<>();
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = new ArrayList<>();
        List<BacTestCultureMedium> BacTestCultureMediumList = new ArrayList<>();
        /*1、查询出检验目的*/
        MPJLambdaWrapper<BacReqPurpose> bacReqPurposeWrapper = new MPJLambdaWrapper<>();
        bacReqPurposeWrapper.eq(BacReqPurpose::getDelFlag, 0);
        bacReqPurposeWrapper.eq(BacReqPurpose::getPurposeNo, "defaultmd");
        List<BacReqPurpose> reqPurposeEntries = bacReqPurposeMapper.selectList(bacReqPurposeWrapper);
        BacReqPurpose reqPurposeEntry = reqPurposeEntries.isEmpty() ? null : reqPurposeEntries.get(0);

        /*2、获取检验目的默认的方案、培养基组合 及流程节点、培养基*/
        BacWorkFlow reqWorkFlowEntry = null;
        List<BacWorkFlowNode> reqWorkFlowNodeList = null;
        if (!BeanUtil.isEmpty(reqPurposeEntry) && StringUtils.isNotEmpty(reqPurposeEntry.getFlowNo())) {
            MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
            bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
            bacWorkFlowWrapper.and(p -> p.eq(BacWorkFlow::getWorkFlowCode, reqPurposeEntry.getFlowNo()).eq(BacWorkFlow::getDelFlag, 0));
            reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);

            /*获取流程方案节点*/
            MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
            bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
            bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
            bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
            reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
        }

        /*3、获取培养基、培养基组合*/
        BacCultureCombination reqCultureCombinationEntry = null;
        List<BacCultureCombinaRel> bacCultureCombinaRelList = null;
        if (!BeanUtil.isEmpty(reqPurposeEntry) && StringUtils.isNotEmpty(reqPurposeEntry.getCulComninaNo())) {
            MPJLambdaWrapper<BacCultureCombination> bacCultureCombinationWrapper = new MPJLambdaWrapper<>();
            bacCultureCombinationWrapper.eq(BacCultureCombination::getDelFlag, 0);
            bacCultureCombinationWrapper.eq(BacCultureCombination::getCode, reqPurposeEntry.getCulComninaNo());
            List<BacCultureCombination> reqCultureCombinationEntries = bacCultureCombinationMapper.selectList(bacCultureCombinationWrapper);
            reqCultureCombinationEntry = reqCultureCombinationEntries.isEmpty() ? null : reqCultureCombinationEntries.get(0);

            MPJLambdaWrapper<BacCultureCombinaRel> BacCultureCombinaRelWrapper = new MPJLambdaWrapper<>();
            BacCultureCombinaRelWrapper.eq(BacCultureCombinaRel::getDelFlag, 0);
            BacCultureCombinaRelWrapper.and(p -> p.eq(BacCultureCombinaRel::getCulCombinaNo, reqPurposeEntry.getCulComninaNo()).eq(BacCultureCombinaRel::getDelFlag, 0));
            BacCultureCombinaRelWrapper.selectAll(BacCultureCombinaRel.class);
            BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
            BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getType, BacCultureCombinaRel::getKind);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getCode, BacCultureCombinaRel::getCombinationNo);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getName, BacCultureCombinaRel::getCombinationNa);
            BacCultureCombinaRelWrapper.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getCode, BacCultureCombinaRel::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
            BacCultureCombinaRelWrapper.leftJoin(BacCultureCombination.class, "tab2", p -> p.eq(BacCultureCombination::getCode, BacCultureCombinaRel::getCulCombinaNo).eq(BacCultureCombination::getDelFlag, 0));

            bacCultureCombinaRelList = bacCultureCombinaRelMapper.selectList(BacCultureCombinaRelWrapper);
        }

        /*4、插入检验 选用方案  节点  培养基信息*/

        String bacTestWkflwId = IdUtil.getSnowflake().nextId() + "";

        //流程方案
        if (reqWorkFlowEntry != null && BeanUtil.isNotEmpty(reqWorkFlowEntry)) {
            BacTestWorkFlow m = new BacTestWorkFlow();
            m.setId(bacTestWkflwId);
            m.setReqNo(ToolsUtils.isEmpty(reqMain) || ToolsUtils.isEmpty(reqMain.getReqNo()) ? null : reqMain.getReqNo());
            m.setWorkFlowNo(reqWorkFlowEntry.getWorkFlowCode());
            m.setWorkFlowNa(reqWorkFlowEntry.getWorkFlowName());
            m.setSeq(1);
            m.setCulCombinaNos(reqCultureCombinationEntry.getCode());
            if (BeanUtil.isNotEmpty(labMaininfo)) {
                m.setRptGroup(labMaininfo.getRptGroup());
                m.setSampleda(labMaininfo.getSampleda());
                m.setSampleNo(labMaininfo.getSampleNo());
            }
            BacTestWorkFlowList.add(m);
        }

        //流程方案节点
        if (!BeanUtil.isEmpty(reqWorkFlowNodeList) && !reqWorkFlowNodeList.isEmpty()) {
            for (BacWorkFlowNode m : reqWorkFlowNodeList) {
                BacTestWorkFlowNode op = new BacTestWorkFlowNode();
                op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                op.setNodeNo(m.getNodeCode());
                op.setReqNo(ToolsUtils.isEmpty(reqMain) || ToolsUtils.isEmpty(reqMain.getReqNo()) ? null : reqMain.getReqNo());
                op.setSeq(m.getSeq());
                if (ToolsUtils.isNotEmpty(labMaininfo)) {
                    op.setRptGroup(labMaininfo.getRptGroup());
                    op.setSampleda(labMaininfo.getSampleda());
                    op.setSampleNo(labMaininfo.getSampleNo());
                }
                BacTestWorkFlowNodeList.add(op);
            }
        }

        //选用的培养基
        if (!BeanUtil.isEmpty(bacCultureCombinaRelList) && !bacCultureCombinaRelList.isEmpty()) {
            for (BacCultureCombinaRel m : bacCultureCombinaRelList) {
                BacTestCultureMedium op = new BacTestCultureMedium();
                op.setReqNo(ToolsUtils.isEmpty(reqMain) || ToolsUtils.isEmpty(reqMain.getReqNo()) ? null : reqMain.getReqNo());
                op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                String a = sysRuleSetService.createRuleCodeList("CultuBarCode", 1).get(0);
                op.setAutoNo(a);
                op.setCultureNo(m.getCultrueNo());
                op.setCultureNa(m.getCultrueName());
                op.setCultureCombinNo(m.getCombinationNo());
                op.setCultureCombinNa(m.getCombinationNa());
                op.setIsPrintLabel(0);
                op.setPrintLabelCount(0);
                try {
                    op.setSeq(Integer.parseInt(m.getOrderNum()));
                } catch (Exception e) {
                    //TODO
                }
                if (ToolsUtils.isNotEmpty(labMaininfo)) {
                    op.setRptGroup(labMaininfo.getRptGroup());
                    op.setSampleda(labMaininfo.getSampleda());
                    op.setSampleNo(labMaininfo.getSampleNo());
                }
                BacTestCultureMediumList.add(op);
            }
        }

        saveWkflwNodesCultuMediums(BacTestWorkFlowList, BacTestWorkFlowNodeList, BacTestCultureMediumList);

        if (reqMain != null && BeanUtil.isNotEmpty(reqMain)) {
            reqMain.setPurposeNo("defaultmd");
            this.saveOrUpdate(reqMain);
        }

        return true;
    }

    /*切换方案的逻辑*/
    public Boolean bacTestUpdateWorkFlow(LabReqMain reqMain, LabMaininfo labMaininfo) {

        MPJLambdaWrapper<BacTestWorkFlow> bacTestWorkFlowQuery = new MPJLambdaWrapper<>();
        bacTestWorkFlowQuery.eq(BacTestWorkFlow::getDelFlag, 0);
        bacTestWorkFlowQuery.and(p -> p.eq(BacTestWorkFlow::getReqNo, reqMain.getReqNo()).eq(BacTestWorkFlow::getDelFlag, 0));
        bacTestWorkFlowQuery.eq(ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getSampleNo()), BacTestWorkFlow::getSampleNo, labMaininfo.getSampleNo());
        bacTestWorkFlowQuery.eq(ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getRptGroup()), BacTestWorkFlow::getRptGroup, labMaininfo.getRptGroup());
        if (ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getSampleda())) {
            Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            bacTestWorkFlowQuery.ge(BacTestWorkFlow::getSampleda, startTime);
            bacTestWorkFlowQuery.le(BacTestWorkFlow::getSampleda, endTime);
        }
        List<BacTestWorkFlow> BacTestWorkFlowList = bacTestWorkFlowMapper.selectList(bacTestWorkFlowQuery);

        for (BacTestWorkFlow m : BacTestWorkFlowList) {
            m.setRptGroup(labMaininfo.getRptGroup());
            m.setSampleda(labMaininfo.getSampleda());
            m.setSampleNo(labMaininfo.getSampleNo());
            bacTestWorkFlowMapper.updateById(m);
        }


        MPJLambdaWrapper<BacTestWorkFlowNode> bacTestWorkFlowNodeQuery = new MPJLambdaWrapper<>();
        bacTestWorkFlowNodeQuery.eq(BacTestWorkFlowNode::getDelFlag, 0);
        bacTestWorkFlowNodeQuery.and(p -> p.eq(BacTestWorkFlowNode::getReqNo, reqMain.getReqNo()).eq(BacTestWorkFlowNode::getDelFlag, 0));
        bacTestWorkFlowNodeQuery.eq(ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getSampleNo()), BacTestWorkFlowNode::getSampleNo, labMaininfo.getSampleNo());
        bacTestWorkFlowNodeQuery.eq(ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getRptGroup()), BacTestWorkFlowNode::getRptGroup, labMaininfo.getRptGroup());
        if (ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getSampleda())) {
            Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            bacTestWorkFlowNodeQuery.ge(BacTestWorkFlowNode::getSampleda, startTime);
            bacTestWorkFlowNodeQuery.le(BacTestWorkFlowNode::getSampleda, endTime);
        }
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = bacTestWorkFlowNodeMapper.selectList(bacTestWorkFlowNodeQuery);
        for (BacTestWorkFlowNode m : BacTestWorkFlowNodeList) {
            m.setRptGroup(labMaininfo.getRptGroup());
            m.setSampleda(labMaininfo.getSampleda());
            m.setSampleNo(labMaininfo.getSampleNo());
            bacTestWorkFlowNodeMapper.updateById(m);
        }


        /*培养基*/
        MPJLambdaWrapper<BacTestCultureMedium> bacTestCultureMediumMPJLambdaWrapper = new MPJLambdaWrapper<>();
        bacTestCultureMediumMPJLambdaWrapper.eq(BacTestCultureMedium::getDelFlag, 0);
        bacTestCultureMediumMPJLambdaWrapper.and(p -> p.eq(BacTestCultureMedium::getReqNo, reqMain.getReqNo()).eq(BacTestCultureMedium::getDelFlag, 0));
        bacTestCultureMediumMPJLambdaWrapper.eq(ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getSampleNo()), BacTestCultureMedium::getSampleNo, labMaininfo.getSampleNo());
        bacTestCultureMediumMPJLambdaWrapper.eq(ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getRptGroup()), BacTestCultureMedium::getRptGroup, labMaininfo.getRptGroup());
        if (ToolsUtils.isNotEmpty(labMaininfo) && ToolsUtils.isNotEmpty(labMaininfo.getSampleda())) {
            Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            bacTestCultureMediumMPJLambdaWrapper.ge(BacTestCultureMedium::getSampleda, startTime);
            bacTestCultureMediumMPJLambdaWrapper.le(BacTestCultureMedium::getSampleda, endTime);
        }
        List<BacTestCultureMedium> bacTestCultureMediumList = bacTestCultureMediumMapper.selectList(bacTestCultureMediumMPJLambdaWrapper);
        for (BacTestCultureMedium m : bacTestCultureMediumList) {
            m.setRptGroup(labMaininfo.getRptGroup());
            m.setSampleda(labMaininfo.getSampleda());
            m.setSampleNo(labMaininfo.getSampleNo());
            bacTestCultureMediumMapper.updateById(m);
        }

//&& CollectionUtils.isEmpty(bacTestCultureMediumList)
        if (CollectionUtils.isEmpty(BacTestWorkFlowList) && CollectionUtils.isEmpty(BacTestWorkFlowNodeList) && CollectionUtils.isEmpty(bacTestCultureMediumList)) {
            /*计算方案的使用*/
            this.CalcWkflwCultures(reqMain, labMaininfo);
        }

        return true;
    }

    /*已走签收扫码上机的逻辑*/
    public Boolean bacTestUpdateWorkFlowV1(LabReqMain reqMain, LabMaininfo labMaininfo) {

        MPJLambdaWrapper<BacTestWorkFlow> bacTestWorkFlowQuery = new MPJLambdaWrapper<>();
        bacTestWorkFlowQuery.eq(BacTestWorkFlow::getDelFlag, 0);
        bacTestWorkFlowQuery.and(p -> p.eq(BacTestWorkFlow::getReqNo, reqMain.getReqNo()).eq(BacTestWorkFlow::getDelFlag, 0));
        List<BacTestWorkFlow> BacTestWorkFlowList = bacTestWorkFlowMapper.selectList(bacTestWorkFlowQuery);

        for (BacTestWorkFlow m : BacTestWorkFlowList) {
            m.setRptGroup(labMaininfo.getRptGroup());
            m.setSampleda(labMaininfo.getSampleda());
            m.setSampleNo(labMaininfo.getSampleNo());
            bacTestWorkFlowMapper.updateById(m);
        }

        MPJLambdaWrapper<BacTestWorkFlowNode> bacTestWorkFlowNodeQuery = new MPJLambdaWrapper<>();
        bacTestWorkFlowNodeQuery.eq(BacTestWorkFlowNode::getDelFlag, 0);
        bacTestWorkFlowNodeQuery.and(p -> p.eq(BacTestWorkFlowNode::getReqNo, reqMain.getReqNo()).eq(BacTestWorkFlowNode::getDelFlag, 0));
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = bacTestWorkFlowNodeMapper.selectList(bacTestWorkFlowNodeQuery);
        for (BacTestWorkFlowNode m : BacTestWorkFlowNodeList) {
            m.setRptGroup(labMaininfo.getRptGroup());
            m.setSampleda(labMaininfo.getSampleda());
            m.setSampleNo(labMaininfo.getSampleNo());
            bacTestWorkFlowNodeMapper.updateById(m);
        }

        /*培养基*/
        MPJLambdaWrapper<BacTestCultureMedium> bacTestCultureMediumMPJLambdaWrapper = new MPJLambdaWrapper<>();
        bacTestCultureMediumMPJLambdaWrapper.selectAll(BacTestCultureMedium.class);
        bacTestCultureMediumMPJLambdaWrapper.selectAs("tb1", BacCultureMedium::getMediumType, BacTestCultureMedium::getMediumType);
        bacTestCultureMediumMPJLambdaWrapper.eq(BacTestCultureMedium::getDelFlag, 0);
        bacTestCultureMediumMPJLambdaWrapper.leftJoin(BacCultureMedium.class, "tb1", p -> p.eq(BacCultureMedium::getCode, BacTestCultureMedium::getCultureNo));
        bacTestCultureMediumMPJLambdaWrapper.and(p -> p.eq(BacTestCultureMedium::getReqNo, reqMain.getReqNo()).eq(BacTestCultureMedium::getDelFlag, 0));
        List<BacTestCultureMedium> bacTestCultureMediumList = bacTestCultureMediumMapper.selectList(bacTestCultureMediumMPJLambdaWrapper);
        for (BacTestCultureMedium m : bacTestCultureMediumList) {
            m.setRptGroup(labMaininfo.getRptGroup());
            m.setSampleda(labMaininfo.getSampleda());
            m.setSampleNo(labMaininfo.getSampleNo());
            bacTestCultureMediumMapper.updateById(m);
        }

        if (CollectionUtils.isEmpty(BacTestWorkFlowList) && CollectionUtils.isEmpty(BacTestWorkFlowNodeList) && CollectionUtils.isEmpty(bacTestCultureMediumList)) {
            /*计算方案的使用*/
            this.CalcWkflwCultures(reqMain, labMaininfo);
        }
        savaDefaultResult(BacTestWorkFlowNodeList, bacTestCultureMediumList, reqMain, labMaininfo);
        return true;
    }

    //插入默认结果
    public void savaDefaultResult(List<BacTestWorkFlowNode> BacTestWorkFlowNodeList, List<BacTestCultureMedium> bacTestCultureMediumList, LabReqMain reqMain, LabMaininfo labMaininfo) {
        if (CollectionUtils.isEmpty(BacTestWorkFlowNodeList)) {
            MPJLambdaWrapper<BacTestWorkFlowNode> bacTestWorkFlowNodeQuery = new MPJLambdaWrapper<>();
            bacTestWorkFlowNodeQuery.eq(BacTestWorkFlowNode::getDelFlag, 0);
            bacTestWorkFlowNodeQuery.and(p -> p.eq(BacTestWorkFlowNode::getReqNo, reqMain.getReqNo()).eq(BacTestWorkFlowNode::getDelFlag, 0));
            BacTestWorkFlowNodeList = bacTestWorkFlowNodeMapper.selectList(bacTestWorkFlowNodeQuery);
        }


        //获取系统参数
        /*报告单元系统选项，微生物药敏报告是否拆分报告*/
        Boolean isDefaultFem = false;
        boolean hasYQPY = BacTestWorkFlowNodeList.stream()
                .anyMatch(node -> "YQPY".equals(node.getNodeNo()));
        boolean hasJINGJIAN = BacTestWorkFlowNodeList.stream()
                .anyMatch(node -> "JINGJIAN".equals(node.getNodeNo()));
        boolean hasStaining = BacTestWorkFlowNodeList.stream()
                .anyMatch(node -> "STAINING".equals(node.getNodeNo()));
        List<BacTestWorkFlowNode> collect = BacTestWorkFlowNodeList.stream().filter(node -> "STAINING".equals(node.getNodeNo())).collect(Collectors.toList());
        try {
            SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(labMaininfo.getOrgId(), "wswsjjdmrscyxbg", labMaininfo.getRptGroup(), null);
            String wswymbgsfhbbg = paramResult.getValueStr();
            if (ToolsUtils.isNotEmpty(wswymbgsfhbbg) && "1".equals(wswymbgsfhbbg)) {
                isDefaultFem = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 根据方案查找阴性结果默认值
        if (isDefaultFem){
            List<BacFlowDefResult> bacFlowDefResults = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(BacTestWorkFlowNodeList)) {
                /*查询阴性结果默认值列表*/
                MPJLambdaWrapper<BacFlowDefResult> flowDefResultWrapper = new MPJLambdaWrapper<>();
                flowDefResultWrapper.eq(BacFlowDefResult::getFlowNo, BacTestWorkFlowNodeList.get(0).getTestFlowNo());
                flowDefResultWrapper.eq(BacFlowDefResult::getDelFlag, 0);
                bacFlowDefResults = bacFlowDefResultMapper.selectList(flowDefResultWrapper);
            }
            //插入药敏鉴定结果
            List<BacFlowDefResult> jingjianResultes = bacFlowDefResults.stream().filter(bacFlowDefResult -> ToolsUtils.isNotEmpty(bacFlowDefResult.getFlowNodes())&&bacFlowDefResult.getFlowNodes().contains("JINGJIAN")).collect(Collectors.toList());
            if (hasJINGJIAN && CollectionUtils.isNotEmpty(jingjianResultes)) {
                List<BacTestResult> bacFlowDefResult = getBacFlowDefResult(BacTestWorkFlowNodeList.get(0).getTestFlowNo(), labMaininfo, jingjianResultes);
                if (CollectionUtils.isNotEmpty(bacFlowDefResult)) {
                    bacTestResultService.saveBatch(bacFlowDefResult);
                }
            }
            //插入染色结果
            MPJLambdaWrapper<LabFeeItem> feeItemWrapper = new MPJLambdaWrapper<>();
            feeItemWrapper.selectAll(LabFeeItem.class);
            feeItemWrapper.leftJoin(LabReqdetail.class, "ld", p -> p.eq(LabReqdetail::getDelFlag, 0).eq(LabReqdetail::getReqNo, reqMain.getReqNo()).eq(LabReqdetail::getFeeCode, LabFeeItem::getFeeCode));
            feeItemWrapper.eq(LabFeeItem::getDelFlag, 0);
            List<LabFeeItem> feeItemList = labFeeItemMapper.selectList(feeItemWrapper);
            if (hasStaining && CollectionUtils.isNotEmpty(feeItemList)) {
                for (LabFeeItem labFeeItem : feeItemList) {
                    if (StringUtils.isNotBlank(labFeeItem.getStainingResult())) {
                        BacStainingResult bacStainingResult = new BacStainingResult();
                        bacStainingResult.setRptGroup(labMaininfo.getRptGroup());
                        bacStainingResult.setSampleda(labMaininfo.getSampleda());
                        bacStainingResult.setSampleNo(labMaininfo.getSampleNo());
                        bacStainingResult.setDescText(labFeeItem.getStainingResult());
                        bacStainingResult.setCulMediumNo("defaultpyj");
                        bacStainingResult.setHandleType("0");
                        bacStainingResult.setTestNodeNo("STAINING");
                        bacStainingResult.setTestFlowNo(collect.get(0).getTestFlowNo());
                        bacStainingResult.setIsDefault(1);
                        bacStainingResult.setIsAlarm(0);
                        bacStainingResult.setIsPushSecReport(0);
                        bacStainingResultMapper.insert(bacStainingResult);
                    }
                }
            }
            /*培养基*/
            if (CollectionUtils.isEmpty(bacTestCultureMediumList)) {
                MPJLambdaWrapper<BacTestCultureMedium> bacTestCultureMediumMPJLambdaWrapper = new MPJLambdaWrapper<>();
                bacTestCultureMediumMPJLambdaWrapper.selectAll(BacTestCultureMedium.class);
                bacTestCultureMediumMPJLambdaWrapper.selectAs("tb1", BacCultureMedium::getMediumType, BacTestCultureMedium::getMediumType);
                bacTestCultureMediumMPJLambdaWrapper.eq(BacTestCultureMedium::getDelFlag, 0);
                bacTestCultureMediumMPJLambdaWrapper.leftJoin(BacCultureMedium.class, "tb1", p -> p.eq(BacCultureMedium::getCode, BacTestCultureMedium::getCultureNo));
                bacTestCultureMediumMPJLambdaWrapper.and(p -> p.eq(BacTestCultureMedium::getReqNo, reqMain.getReqNo()).eq(BacTestCultureMedium::getDelFlag, 0));
                bacTestCultureMediumList = bacTestCultureMediumMapper.selectList(bacTestCultureMediumMPJLambdaWrapper);
            }
            for (BacTestCultureMedium m : bacTestCultureMediumList) {
                boolean isPing = "2".equals(m.getMediumType());
                //判断用不用节点默认结果
                if (hasYQPY && isPing) {
                    String defaultResult = "";
                    Optional<BacFlowDefResult> result = bacFlowDefResults.stream()
                            .filter(bacFlowDefResult -> bacFlowDefResult.getFlowNodes().contains("YQPY"))
                            .findFirst();
                    if (result.isPresent()) {
                        defaultResult = result.get().getDefNa();
                    }
                    if (ToolsUtils.isNotEmpty(defaultResult)) {
                        BacBloodCultrue bacBloodCultrue = new BacBloodCultrue();
                        bacBloodCultrue.setCulMediumNo(m.getCultureNo());
                        bacBloodCultrue.setCulMediumNa(m.getCultureNa());
                        bacBloodCultrue.setResult(defaultResult);
                        bacBloodCultrue.setTestNodeNo("YQPY");
                        bacBloodCultrue.setTestFlowNo(collect.get(0).getTestFlowNo());
                        bacBloodCultrue.setReqNo(labMaininfo.getReqNo());
                        bacBloodCultrue.setIsPositive(0);
                        bacBloodCultrue.setTestTime(new Timestamp(System.currentTimeMillis()));
                        bacBloodCultrue.setIsAlarm((double) 0);
                        bacBloodCultrue.setIsPollute((double) 0);
                        bacBloodCultrue.setIsPositive(0);
                        bacBloodCultrue.setRptGroup(labMaininfo.getRptGroup());
                        bacBloodCultrue.setSampleda(labMaininfo.getSampleda());
                        bacBloodCultrue.setSampleNo(labMaininfo.getSampleNo());
                        bacBloodCultrueMapper.insert(bacBloodCultrue);
                    }
                }
            }
        }

    }

    public List<BacTestResult> getBacFlowDefResult(String workFlowNo, LabMaininfo labMaininfo, List<BacFlowDefResult> flowDefResultList) {
        if (ToolsUtils.isNotEmpty(flowDefResultList)) {
            //根据默认结果生成阴性结果
            List<BacTestResult> addbacTestResults = new ArrayList<>();
            for (int i = 0; i < flowDefResultList.size(); i++) {
                BacFlowDefResult bacFlowDefResult = flowDefResultList.get(i);

                BacTestResult bacTestResult = new BacTestResult();
                bacTestResult.setSampleda(labMaininfo.getSampleda());
                bacTestResult.setRptGroup(labMaininfo.getRptGroup());
                bacTestResult.setSampleNo(labMaininfo.getSampleNo());
                bacTestResult.setIsolateNum("Def"+String.valueOf(i + 1));
                String defNa = bacFlowDefResult.getDefNa();
                //defNa是否包含[day]，如果不包含直接赋值，如果包含则获取当前时间与testTime作比较查看过了多少天
                if (defNa.contains("[day]")) {
                    Timestamp testTime = labMaininfo.getTestTime();
                    if (ToolsUtils.isNotEmpty(testTime)) {
                        try {
                            // 将Timestamp转换为LocalDate
                            LocalDate startDate = testTime.toLocalDateTime().toLocalDate();
                            LocalDate endDate = new Timestamp(new Date().getTime()).toLocalDateTime().toLocalDate();
                            // 计算两个日期之间的天数差
                            long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
                            defNa = defNa.replace("[day]", String.valueOf(daysBetween));
                            bacTestResult.setGermNa(defNa);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    bacTestResult.setGermNa(bacFlowDefResult.getDefNa());
                }
                bacTestResult.setOperateDate(new Timestamp(new Date().getTime()));
                SysUser sysUser = RedisUserManager.getUser();
                if (ToolsUtils.isNotEmpty(sysUser)) {
                    bacTestResult.setOperateUserNo(sysUser.getRealname());
                }
                bacTestResult.setTestFlowNo(workFlowNo);
                bacTestResult.setTestNodeNo("JINGJIAN");
                bacTestResult.setIsAlarm(false);
                bacTestResult.setIsDrugAlarm(false);
                bacTestResult.setIsContagion(false);
                addbacTestResults.add(bacTestResult);

            }
            return addbacTestResults;

        }
        return null;
    }
}
